package th.ac.tu.engr.timemylife;

import android.content.SharedPreferences;
import android.util.Log;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

import android.os.AsyncTask;


public class ServerAsyncTask extends AsyncTask<URL, Void, Integer> {
    private final String TAG = "ServerRegisterTask";


    @Override
    protected void	onPreExecute() {
    }

    @Override
    protected Integer doInBackground(URL... urls) {
        int id = 0;
        try {
            URL url = urls[0];
            URLConnection conn = url.openConnection();
            conn.connect();
            InputStream is = conn.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));

            StringBuilder builder = new StringBuilder();
            String aux = "";
            while ((aux = reader.readLine()) != null) {
                builder.append(aux);
            }

            String jsonString = builder.toString();

            try {

                JSONObject jsonObj = new JSONObject(jsonString);

                Log.v(TAG, "Before getInt ID");

                id = jsonObj.getInt("id");
                Log.v(TAG, "ID = " + id);

                SharedPreferences pref = MyApp.getAppPreference();
                SharedPreferences.Editor pref_editor = pref.edit();
                pref_editor.putInt("ID", id);
                pref_editor.commit();

                Log.v(TAG, "Save ID to Preference");



            }
            catch (JSONException j){
                j.printStackTrace();
            }
        }
        catch(IOException e){
            e.printStackTrace();
        }
        return id;
    }

    @Override
    protected void onProgressUpdate(Void... values) {
    }

    @Override
    protected void onPostExecute(Integer result) {
        // Save to preference



    }
}
